package com.jinkaimen.goodcash.http;

import android.text.TextUtils;

import com.alibaba.fastjson.JSON;
import com.ht.baselibs.application.HTApplication;
import com.ht.baselibs.bean.BaseGetBean;
import com.ht.baselibs.utils.ChannelUtils;
import com.ht.baselibs.utils.DeviceUtils;
import com.ht.baselibs.utils.SharedPreferencesUtils;
import com.ht.baselibs.utils.UIUtils;
import com.igexin.sdk.PushManager;
import com.jinkaimen.goodcash.bean.ConsultBean;
import com.jinkaimen.goodcash.manager.ApiManager;
import com.jinkaimen.goodcash.service.GetuiService;
import com.jinkaimen.goodcash.service.PushService;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import okhttp3.FormBody;
import okhttp3.Interceptor;
import okhttp3.Protocol;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;

public class ConsultInterceptor implements Interceptor {

    public static final String ACCESS_TOKEN = "access_Token";
    public static final String ENCRYPT_KEY = "encrypt_Key";
    public static final String CONSULT_SERVICE_CODE = "HSY001016";

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request mOriginalRequest = chain.request();

        FormBody body = (FormBody) mOriginalRequest.body();
        String serviceCode = null;
        for (int i = 0; i < body.size(); i++) {
            String paramName = body.name(i);
            if ("serviceCode".equals(paramName)){
                serviceCode = body.value(i);
            }
        }


        if (CONSULT_SERVICE_CODE.equals(serviceCode)){
            return chain.proceed(mOriginalRequest);
        } else {
            int retryTimes = 0;
            String token = SharedPreferencesUtils.getString(ACCESS_TOKEN, "");
            while (TextUtils.isEmpty(token) && retryTimes++ < 3) {
//                if (mConsultData == null){
//                    byte[] encryptData = TripleDes.getInstance().encryptECB(HTApplication.CONSULT_KEY, HTApplication.CONSULT_CONTENT, TripleDes.MODE_ECB);
//                    mConsultData = new String(Base64.encode(encryptData));
//                }

                try {

//                    MessageDigest messageDigest= MessageDigest.getInstance("MD5");
//                    String checkMd5 = Utils.byte2hex(messageDigest.digest(check.getBytes()));


                    Map<String, Object> map = new HashMap<>();

                    map.put("deviceid", DeviceUtils.getDeviceId());
                    map.put("deviceName", DeviceUtils.getDeviceName());
                    map.put("osVersion", DeviceUtils.getOsVersion());
                    map.put("appCode", "hsy");
                    map.put("appVersion", DeviceUtils.getAppVersionName());
                    map.put("appChannel", ChannelUtils.getChannel());

                    retrofit2.Response<ResponseBody> consultCall = ApiManager
                            .getApi()//
                            .consult(
                                    CONSULT_SERVICE_CODE,
                                    JSON.toJSONString(map, false)
                            )//
                            .execute();
                    if (consultCall.isSuccessful()){
                        String result = consultCall.body().string();
                        BaseGetBean baseGetBean = JSON.parseObject(result, BaseGetBean.class);
                        ConsultBean consultBean = JSON.parseObject(baseGetBean.encryptDataResult, ConsultBean.class);
                        SharedPreferencesUtils.put(ACCESS_TOKEN, consultBean.accessToken);
                        SharedPreferencesUtils.put(ENCRYPT_KEY, consultBean.encryptKey);

                        //TODO 在这里上行clientId
                        if (TextUtils.isEmpty(SharedPreferencesUtils.getString(GetuiService.GETUI_CLIEND_ID, ""))){
                            UIUtils.post(new Runnable() {
                                @Override
                                public void run() {
                                    PushManager.getInstance().initialize(HTApplication.getContext(), PushService.class);
                                }
                            });
                        }
                        break;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    break;
                }
            }

            if (TextUtils.isEmpty(SharedPreferencesUtils.getString(ACCESS_TOKEN, ""))){
                //TODO 这个地方表示不用协商 放行
//                if ("HSS001001".equals(serviceCode) || "HSS001005".equals(serviceCode)){
//                    return chain.proceed(mOriginalRequest);
//                } else {
                    return new Response.Builder()
                            .code(1000)
                            .message("协商失败")
                            .request(chain.request())
                            .protocol(Protocol.HTTP_1_1)
                            .build();
//                }
            } else {
                return chain.proceed(mOriginalRequest);
            }

        }
    }
}
